package com.demo.petshop.service.impl;

import com.demo.petshop.entity.VideoLikes;
import com.demo.petshop.entity.Videos;
import com.demo.petshop.mapper.VideoLikesMapper;
import com.demo.petshop.mapper.VideosMapper;
import com.demo.petshop.service.VideoLikesService;
import com.demo.petshop.util.Result;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.sqlite.date.DateFormatUtils;

import java.util.Date;

import static com.demo.petshop.entity.table.VideoLikesTableDef.VIDEO_LIKES;

/**
 *  服务层实现。
 *
 * @author lenovo
 * @since 2025-06-11
 */
@Service
public class VideoLikesServiceImpl extends ServiceImpl<VideoLikesMapper, VideoLikes> implements VideoLikesService {

    @Autowired
    private VideoLikesMapper videoLikesMapper;

    @Autowired
    private VideosMapper videosMapper;

    private int getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getUserId();
    }

    @Override
    public Object like(Integer videoId) {
        Videos videos = videosMapper.selectOneById(videoId);
        videos.setLikes(videos.getLikes() + 1);
        videoLikesMapper.insertOrUpdate(
                new VideoLikes(null, getUserId(), videoId, DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")));
        return Result.success(videosMapper.update(videos));
    }

    @Override
    public Object unlike(Integer videoId) {
        Videos videos = videosMapper.selectOneById(videoId);
        videos.setLikes(videos.getLikes() - 1);
        videosMapper.update(videos);
        return Result.success(videoLikesMapper.deleteByQuery(
                new QueryWrapper()
                        .where(VIDEO_LIKES.VIDEO_ID.eq(videoId))
                        .and(VIDEO_LIKES.USER_ID.eq(getUserId()))
        ));
    }

    @Override
    public Object checkLike(Integer videoId) {
        return Result.success(videoLikesMapper.selectOneByQuery(
                new QueryWrapper()
                        .where(VIDEO_LIKES.VIDEO_ID.eq(videoId))
                        .and(VIDEO_LIKES.USER_ID.eq(getUserId()))
        ));
    }
}
